from sklearn import datasets
from sklearn.cluster import Birch
from sklearn.metrics import silhouette_score

import pandas as pd
import matplotlib.pyplot as plt

# 加载数据集
iris = datasets.load_iris()
iris_data = iris.data

# 进行预处理
iris_df = pd.DataFrame(iris_data, columns=iris.feature_names)

# 构建Birch聚类模型
birch_model = Birch(threshold=0.01, n_clusters=3)

# 训练模型
birch_model.fit(iris_data)

# 预测聚类结果
birch_cluster_labels = birch_model.predict(iris_data)

# 评估模型
silhouette_avg = silhouette_score(iris_data, birch_cluster_labels)
print('轮廓系数:', silhouette_avg)

# 可视化聚类结果
plt.scatter(iris_df['sepal length (cm)'], iris_df['sepal width (cm)'],
            c=birch_cluster_labels, cmap='viridis')
plt.xlabel('Sepal length (cm)')
plt.ylabel('Sepal width (cm)')
plt.show()